package com.htfyun.roobofactory;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.hardware.Camera;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.htfyun.roobofactory.config.AppConfig;
import com.htfyun.roobofactory.config.RooboBuildConfig;
import com.htfyun.roobofactory.htfyunUtils.BatteryInfo;
import com.htfyun.roobofactory.utils.FileReadWrite;
import com.htfyun.roobofactory.utils.PermissionManager;
import com.htfyun.roobofactory.view.CameraPreview;
import com.htfyun.roobofactory.wifilibrary.WiFiManager;
import com.htfyun.roobofactory.wifilibrary.listener.OnWifiEnabledListener;
import com.roobo.hardware.KeyEventManager;
import com.roobo.hardware.LedCtrlManager;

import java.io.File;
import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.Date;

import static com.htfyun.roobofactory.htfyunUtils.MakeTimeUtils.makeTimeString;

/**
 * Created by sst on 2018/7/31.
 */

public class AgingTestActivity extends BaseActivity {

    private FrameLayout frameLayout;

    private TextView txtCameraFrontInfo;
    private TextView txtProximitySensorData;
    private TextView txtLightSensorData;
    private TextView txtKey;
    private TextView txtLed;
    private TextView txtWifi;
    private TextView txtBluetooth;
    private TextView txtBatteryInfo;

    private TextView txtAgingTime;
    private long timeAgingStart_ms = 0;

    private Button btnMusicCtrl;
    private Button btnFinish;
    private Button btnAgingKeep;
    private boolean isAgingKeep = false;

    // camera test
    private CameraPreview preview;
    private Camera frontCamera = null;
//    public int mFrontPreviewW = 1280;// 1280; // 1920;
//    public int mFrontPreviewH = 720; // 720; // 1080;
//    public int mFrontPreviewFPS = 20; // 480;
    private int mCameraPreviewFPSReal = 0;

    private Handler mHandler;

    private Context mContext;

    private SensorManager mSensorManager;
    private Sensor mSensorProximity = null;
    private Sensor mSensorLight = null;

    private KeyEventManager keyEventManager = KeyEventManager.getInstance();
    private LedCtrlManager mLedCtrlManager = LedCtrlManager.getInstance();

    private WiFiManager mWiFiManager;
    private BluetoothAdapter bluetoothAdapter;

    private BatteryInfo batteryInfo;

    private MediaPlayer mediaPlayer = null;
    private AudioManager mAudioManager = null;

    private final static long AGING_TIME_MS = AppConfig.AGING_TIME_MS;

    /*
  * the data is :len = sprintf(_buf,"adc_now=%d,adc_avg=%d,volt_pure=%d,cap=%d,charge_type=%s,"
     "volt_adjusted=%d,adjust=%d,adc_calib=%d,gpio charge_ok=%d\n"
  */
    private static final String BATTERY_ADC_LOG_PATH = "/sys/class/bat-dbg/adc";

    private String mBatteryTestLogFilePathString;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_aging_test);

        mContext = this;
        mHandler = new MyHandler(this);

        timeAgingStart_ms = System.currentTimeMillis();

        batteryInfo = new BatteryInfo(this);

        frameLayout = (FrameLayout) findViewById(R.id.layout_top_frame);

        txtCameraFrontInfo = (TextView) findViewById(R.id.txtCameraFrontInfo);
        txtProximitySensorData = (TextView) findViewById(R.id.txtProximitySensorData);
        txtLightSensorData = (TextView) findViewById(R.id.txtLightSensorData);
        txtKey = (TextView) findViewById(R.id.txtKey);
        txtLed = (TextView) findViewById(R.id.txtLed);
        txtWifi = (TextView) findViewById(R.id.txtWifi);
        txtBluetooth = (TextView) findViewById(R.id.txtBluetooth);
        txtBatteryInfo = (TextView) findViewById(R.id.txtBatteryInfo);
        txtAgingTime = (TextView) findViewById(R.id.txtAgingTime);
        btnMusicCtrl = (Button) findViewById(R.id.btnMusicCtrl);


        mWiFiManager = WiFiManager.getInstance(mContext);

        mWiFiManager.setOnWifiEnabledListener(new OnWifiEnabledListener() {
            @Override
            public void onWifiEnabled(boolean enabled) {
                int statusResId = R.string.wifi_status_off;
                if (enabled) {
                    statusResId = R.string.wifi_status_on;
                }

                txtWifi.setText(getString(R.string.test_wifi_status, getString(statusResId)));

            }
        });

        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (bluetoothAdapter == null) {

            txtBluetooth.setText(R.string.test_bt_unsupported);
            txtBluetooth.setTextColor(Color.RED);

        }

        btnMusicCtrl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                int resId = R.string.aging_music_play;
                if (mediaPlayer == null) {
                    initMediaPlayer();
                    resId = R.string.aging_music_stop;
                } else {
                    deinitMediaPlayer();
                }

                btnMusicCtrl.setText(resId);

            }
        });

        btnFinish = (Button) findViewById(R.id.btnFinish);
        btnFinish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ActivityCompat.finishAfterTransition(getActivity());
            }
        });

        btnAgingKeep = (Button) findViewById(R.id.btnAgingKeep);
        isAgingKeep = false;
        btnAgingKeep.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

               isAgingKeep = true;
               v.setEnabled(false);

            }
        });

    }

    @Override
    protected void onResume() {
        super.onResume();

        initPermission();


        batteryInfo.startMonitor();
        batteryInfo.setOnBatteryChangedListener(new BatteryInfo.OnBatteryChangedListener() {
            @Override
            public void onBatteryChangedListener() {
                String info = getString(R.string.info_battery,
                        batteryInfo.getBatteryVoltage(),
                        batteryInfo.getBatteryLevel(),
                        batteryInfo.getBatteryStatusString());

                txtBatteryInfo.setText(info);
            }
        });

        sensorInit();

        ledStart();

        wifiStart();

        btStart();

        mHandler.sendEmptyMessage(MSG_UPDATE_AGING_TIME);



    }

    @Override
    protected void onPause() {
        super.onPause();

        batteryInfo.setOnBatteryChangedListener(null);
        batteryInfo.stopMonitor();

        cameraDeinit();

        sensorDeinit();

        ledStop();

        wifiStop();

        btStop();

        deinitMediaPlayer();

        mHandler.removeMessages(MSG_UPDATE_AGING_TIME);

        batteryADCLogStop();


    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        String status = getString(R.string.engineer_test_current_keycode_status_down);
        String name = "null";
        int pinLevel = 0;
        KeyEventManager.RK_KEYS rooboKeysAttr = keyEventManager.getRKKeysByKeyCode((keyCode));
        if (rooboKeysAttr != null) {
            name = rooboKeysAttr.getKeyLabel();
            pinLevel = keyEventManager.getKeyState(rooboKeysAttr) ? 1 : 0;
        }
        txtKey.setText(getString(R.string.engineer_test_current_keycode, keyCode, status, name, pinLevel));

        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {

        String status = getString(R.string.engineer_test_current_keycode_status_up);
        String name = "null";
        int pinLevel = 0;
        KeyEventManager.RK_KEYS rooboKeysAttr = keyEventManager.getRKKeysByKeyCode((keyCode));
        if (rooboKeysAttr != null) {
            name = rooboKeysAttr.getKeyLabel();
            pinLevel = keyEventManager.getKeyState(rooboKeysAttr) ? 1 : 0;
        }
        txtKey.setText(getString(R.string.engineer_test_current_keycode, keyCode, status, name, pinLevel));


        return super.onKeyUp(keyCode, event);
    }

    @Override
    public boolean onKeyLongPress(int keyCode, KeyEvent event) {

        String status = getString(R.string.engineer_test_current_keycode_status_down_long);
        String name = "null";
        int pinLevel = 0;
        KeyEventManager.RK_KEYS rooboKeysAttr = keyEventManager.getRKKeysByKeyCode((keyCode));
        if (rooboKeysAttr != null) {
            name = rooboKeysAttr.getKeyLabel();
            pinLevel = keyEventManager.getKeyState(rooboKeysAttr) ? 1 : 0;
        }
        txtKey.setText(getString(R.string.engineer_test_current_keycode, keyCode, status, name, pinLevel));

        return super.onKeyLongPress(keyCode, event);
    }

    private void initPermission() {

        if (
                ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                ) {

            //同时申请多个权限
            PermissionManager.getInstance(getApplicationContext()).execute(this,
                    Manifest.permission.CAMERA,
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
            );

        } else {

            camreaInit();

            batteryADCLogStart();


        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.getInstance(getApplicationContext()).
                onRequestPermissionsResult(requestCode, permissions, grantResults);

        Log.e(TAG, "mic ~~~~~~~~~~~~~~onRequestPermissionsResult");

        camreaInit();
        batteryADCLogStart();

    }

    private void updateCameraPreviewInfo(int realFps ){
        Camera.Size previewSize = preview.getmPreviewSize();
        int maxFPS = preview.getMaxFPS() / 1000;

        String info = getString(R.string.camera_front_info, previewSize.width, previewSize.height, maxFPS, realFps);
        txtCameraFrontInfo.setText(info);
        txtCameraFrontInfo.setTextColor(Color.BLUE);
    }

    private void camreaInit() {

        openCamera();

        if( preview == null ) {
            preview = new CameraPreview(mContext, frontCamera);
            preview.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            frameLayout.addView(preview, 0);
        }
        preview.setKeepScreenOn(true);
    }


    private void openCamera() {

        int numCams = Camera.getNumberOfCameras();
        Log.d(TAG, "Number of Cameras=" + numCams);
        if (numCams > 0) {
            try {
                if (frontCamera == null) {
                    frontCamera = Camera.open(0);
                }
            } catch (RuntimeException ex) {
                txtCameraFrontInfo.setText(R.string.camera_open_failed);
                txtCameraFrontInfo.setTextColor(Color.RED);
                frontCamera = null;
            }

            if (frontCamera != null) {
                // will be set and start at CameraPreview
                frontCamera.setPreviewCallback(new Camera.PreviewCallback() {
                    @Override
                    public void onPreviewFrame(byte[] data, Camera camera) {
                        mCameraPreviewFPSReal++;
                    }
                });
                mHandler.sendEmptyMessageDelayed(MSG_CALC_CAMERA_FSP, PERIOD_CALC_CAMERA_FSP);
                mCameraPreviewFPSReal = 0;
            }
        } else {
            txtCameraFrontInfo.setText(R.string.camera_not_found);
            txtCameraFrontInfo.setTextColor(Color.RED);
        }
    }

    private void cameraDeinit() {

        mHandler.removeMessages(MSG_CALC_CAMERA_FSP);

        if (frontCamera != null) {

            frontCamera.setPreviewCallback(null);

            frameLayout.removeView(preview);

            frontCamera.stopPreview();
            frontCamera.release();
            frontCamera = null;

        }

    }


    private void sensorInit() {
        mSensorManager = (SensorManager) this.getSystemService(Context.SENSOR_SERVICE);
        if (mSensorManager == null) {
            return;
        }
        mSensorProximity = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
        boolean result_ok = mSensorManager.registerListener(mSensorEventListener,
                mSensorProximity, SensorManager.SENSOR_DELAY_NORMAL);
        if (!result_ok) {
            txtProximitySensorData.setText(R.string.aging_proximity_sensor_failed);
            txtProximitySensorData.setTextColor(Color.RED);

        }

        mSensorLight = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
        result_ok = mSensorManager.registerListener(mSensorEventListener,
                mSensorLight, SensorManager.SENSOR_DELAY_NORMAL);
        if (!result_ok) {
            txtLightSensorData.setText(R.string.aging_light_sensor_failed);
            txtLightSensorData.setTextColor(Color.RED);
        }


    }

    private void sensorDeinit() {
        if (mSensorManager != null) {
            mSensorManager.unregisterListener(mSensorEventListener);
            mSensorProximity = null;
            mSensorLight = null;
        }
    }

    final SensorEventListener mSensorEventListener = new SensorEventListener() {

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {
            Log.i(TAG, "onAccuracyChanged");
        }

        @Override
        public void onSensorChanged(SensorEvent sensorEvent) {
            // TODO Auto-generated method stub
            if (true) {
//                Log.i(TAG,"onSensorChanged");

                //图解中已经解释三个值的含义
                float X_lateral = sensorEvent.values[0];
//                float Y_longitudinal = sensorEvent.values[1];
//                float Z_vertical = sensorEvent.values[2];
                String info;
                if (sensorEvent.sensor.getType() == Sensor.TYPE_LIGHT) {
                    txtLightSensorData.setText(getString(R.string.aging_light_sensor_info, (int) X_lateral));
                    txtLightSensorData.setTextColor(Color.BLUE);

                } else if (sensorEvent.sensor.getType() == Sensor.TYPE_PROXIMITY) {
                    txtProximitySensorData.setText(getString(R.string.aging_proximity_sensor_info, (int) X_lateral));
                    txtProximitySensorData.setTextColor(Color.BLUE);

                }
            }
        }
    };

    private void ledStart() {

        for (int i = 0; i < mLedCtrlManager.getMaxLedNum(LedCtrlManager.LED_NUM_ALL); i++) {
            mLedCtrlManager.setLedLight(i,  mLedCtrlManager.getMaxLedBrightness(LedCtrlManager.LED_ID_LEFT_BASE), 0);
        }
        final boolean on = true;
        mLedCtrlManager.setSingleLedPowerOn(on);
        mLedCtrlManager.setSingleLedRGBRedOn(on);
        mLedCtrlManager.setSingleLedRGBGreenOn(on);
        mLedCtrlManager.setSingleLedRGBBlueOn(on);

        ledUpdateInfo();
    }

    private void ledStop() {

        for (int i = 0; i < mLedCtrlManager.getMaxLedNum(LedCtrlManager.LED_NUM_ALL); i++) {
            mLedCtrlManager.setLedLight(i, 0, 0);
        }
        final boolean on = false;
        mLedCtrlManager.setSingleLedPowerOn(on);
        mLedCtrlManager.setSingleLedRGBRedOn(on);
        mLedCtrlManager.setSingleLedRGBGreenOn(on);
        mLedCtrlManager.setSingleLedRGBBlueOn(on);
    }

    private void ledUpdateInfo() {

        int leftNum = mLedCtrlManager.getMaxLedNum(LedCtrlManager.LED_NUM_LEFT);
        int rightNum = mLedCtrlManager.getMaxLedNum(LedCtrlManager.LED_NUM_RIGHT);
        int maxLight = mLedCtrlManager.getMaxLedBrightness(LedCtrlManager.LED_ID_LEFT_BASE);
        int minLight = mLedCtrlManager.getMinLedBrightness(LedCtrlManager.LED_ID_LEFT_BASE);

        String info = getString(R.string.led_info, leftNum, rightNum, maxLight, minLight);

        txtLed.setText(info);
    }

    private void wifiStart() {
        mWiFiManager.registerWifiReceiver(mContext);
        mHandler.sendEmptyMessage(MSG_TOGGLE_WIFI);
    }

    private void wifiStop() {

        mWiFiManager.unregisterWifiReceiver(mContext);
        mHandler.removeMessages(MSG_TOGGLE_WIFI);

        mWiFiManager.closeWiFi();

    }

    private void wifiToggle() {

        if (!mWiFiManager.isWifiEnabled()) {

            mWiFiManager.openWiFi();

        } else {

            mWiFiManager.closeWiFi();
        }

    }

    private void btStart() {

        if (bluetoothAdapter == null) {
            return;
        }

        registerReceiver(BTReceiver, getIntentFilterOfBT());

        mHandler.sendEmptyMessage(MSG_TOGGLE_BLUETOOTH);

    }

    private void btStop() {
        if (bluetoothAdapter == null) {
            return;
        }

        unregisterReceiver(BTReceiver);

        mHandler.removeMessages(MSG_TOGGLE_BLUETOOTH);

        bluetoothAdapter.disable();

    }

    private void btToggle() {

        if (bluetoothAdapter == null) {
            return;
        }
        if (bluetoothAdapter.isEnabled()) {
            bluetoothAdapter.disable();
        } else {
            bluetoothAdapter.enable();
        }
    }


    private IntentFilter getIntentFilterOfBT() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        return intentFilter;
    }

    private BroadcastReceiver BTReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (action == null) {
                return;
            }

            if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {

                String stateExtra = BluetoothAdapter.EXTRA_STATE;
                int state = intent.getIntExtra(stateExtra, -1);
                int statusResId = R.string.bt_status_unknown;

                switch(state) {
                    case BluetoothAdapter.STATE_TURNING_ON:
                        statusResId = R.string.bt_status_turning_on;
                        break;
                    case BluetoothAdapter.STATE_ON:
                        statusResId = R.string.bt_status_on;
                        break;
                    case BluetoothAdapter.STATE_TURNING_OFF:
                        statusResId = R.string.bt_status_turning_off;
                        break;
                    case BluetoothAdapter.STATE_OFF:
                        statusResId = R.string.bt_status_off;
                        break;
                }

                txtBluetooth.setText(getString(R.string.test_bt_status, getString(statusResId)));
                txtBluetooth.setTextColor(Color.BLUE);

            }
        }
    };



    private void initMediaPlayer() {

        if (mediaPlayer != null) {
            deinitMediaPlayer();
        }

        if (mAudioManager == null) {
            mAudioManager = (AudioManager)getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
        }

        mediaPlayer = MediaPlayer.create(this, R.raw.music_little_apple);
        int currentVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        int maxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        Log.d(TAG,"currentVolume: " + currentVolume + " maxVolume: " + maxVolume);
        mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, maxVolume, 0);
        mediaPlayer.start();//开始音频的播放
        mediaPlayer.setLooping(true);

    }

    private void deinitMediaPlayer() {
        if(mediaPlayer !=null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }

    private void updateAgingTimeUI() {
        long time = System.currentTimeMillis() - timeAgingStart_ms;
        long second = time / 1000;
        String stringTime = makeTimeString(mContext, second);
        String text = getString(R.string.aging_time, stringTime);
        txtAgingTime.setText(text);

        saveAgingTime(time);

        if (time > AGING_TIME_MS && !isAgingKeep) {
            Log.e(TAG, "aging time is bigger than 4 hours");
            ActivityCompat.finishAfterTransition(getActivity());
        }

    }

    private void saveAgingTime(long time_ms) {
        SharedPreferences sp = getActivity().getSharedPreferences(AppConfig.SHARE_PREFERENCE_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();//获取编辑器
        editor.putLong(AppConfig.SHARE_PREFERENCE_KEY_AGING_TIME, time_ms);
        editor.apply();

    }

    private void batteryADCLogStart() {
        if (!RooboBuildConfig.SAVE_BATTERY_ADC_LOG) {
            return;
        }
        mHandler.sendEmptyMessage(MSG_BATTERY_ADC_LOG);
    }

    private void batteryADCLogStop() {
        mHandler.removeMessages(MSG_BATTERY_ADC_LOG);
    }

    private void readAndSaveBatteryADCLog() {
        String adcLog = FileReadWrite.readFileByLines(BATTERY_ADC_LOG_PATH);
        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd_HH-mm-ss: ");//可以方便地修改日期格式
        String dt = dateFormat.format(now);

        if (TextUtils.isEmpty(mBatteryTestLogFilePathString)) {
            mBatteryTestLogFilePathString = getSDcardDateTimeFilePath("Batt_", "txt");
        }
        FileReadWrite.writeAppendFile(mBatteryTestLogFilePathString, dt + adcLog + "\n");

    }

    private static final int MSG_CALC_CAMERA_FSP = 100;
    private static final int PERIOD_CALC_CAMERA_FSP = 1000;

    private static final int MSG_TOGGLE_WIFI = 300;
    private static final int PERIOD_TOGGLE_WIFI = 5000;

    private static final int MSG_TOGGLE_BLUETOOTH = 400;
    private static final int PERIOD_TOGGLE_BLUETOOTH = 5000;

    private static final int MSG_UPDATE_AGING_TIME = 500;
    private static final int PERIDO_UPDATE_AGING_TIEM = 1000;

    private static final int MSG_BATTERY_ADC_LOG = 600;
    private static final int PERIOD_BATTERY_ADC_LOG = 30 * 1000;//30s


    private static final class MyHandler extends Handler {
        private WeakReference<AgingTestActivity> reference;

        protected MyHandler(AgingTestActivity activity) {
            reference = new WeakReference<AgingTestActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            if (reference == null) {
                return;
            }
            AgingTestActivity activity = reference.get();
            if (activity == null) {
                return;
            }

            final int what = msg.what;

            switch (what) {
                case MSG_UPDATE_AGING_TIME:
                    activity.updateAgingTimeUI();
                    sendEmptyMessageDelayed(MSG_UPDATE_AGING_TIME, PERIDO_UPDATE_AGING_TIEM);
                    break;
                case MSG_CALC_CAMERA_FSP: {
                    int curFPS = activity.mCameraPreviewFPSReal;
                    activity.updateCameraPreviewInfo(curFPS);
                    sendEmptyMessageDelayed(MSG_CALC_CAMERA_FSP, PERIOD_CALC_CAMERA_FSP);
                    activity.mCameraPreviewFPSReal = 0;

                    break;
                }

                case MSG_TOGGLE_WIFI:
                    activity.wifiToggle();
                    sendEmptyMessageDelayed(MSG_TOGGLE_WIFI, PERIOD_TOGGLE_WIFI);
                    break;
                case MSG_TOGGLE_BLUETOOTH:
                    activity.btToggle();
                    sendEmptyMessageDelayed(MSG_TOGGLE_BLUETOOTH, PERIOD_TOGGLE_BLUETOOTH);
                    break;
                case MSG_BATTERY_ADC_LOG:
                    activity.readAndSaveBatteryADCLog();
                    sendEmptyMessageDelayed(MSG_BATTERY_ADC_LOG, PERIOD_BATTERY_ADC_LOG);
                    break;
                default:break;

            }

        }
    }


    /*
    * @param prifex -- prifex of the filename.
    * @param ext    -- the extension of the file name( not include "." ).
    * @return -- the filename what is : prifex + datetime + "." + ext;
    */
    private String getFileNameDateTime(String prifex, String ext) {
        String fp;
        Date now = new Date();

        // "yyyy-MM-dd_HH-mm-ss"
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");//可以方便地修改日期格式
        String dt = dateFormat.format(now);
        fp = prifex + dt + "." + ext;
        return fp;
    }

    private String getSDcardDateTimeFilePath(String prifex, String ext) {
        String fp = "";
        File sampleDir = Environment.getExternalStorageDirectory();
        if (!sampleDir.canWrite()) {  // Workaround for broken sdcard support on the device.
            Log.d(TAG, "Can not Write:" + sampleDir.getAbsolutePath());
            sampleDir = new File("/sdcard/sdcard");
        }
        fp = sampleDir.getAbsolutePath() + "/";
        fp = getFileNameDateTime(fp + prifex, ext);

        return fp;
    }


}
